import {isBrowser} from "./utils";
import mitt, {Emitter} from 'mitt';

interface OverlayConfig {
  bgColor: string;
  pointerEvents: string;
  animated: boolean;
}

const defConfig = {
  bgColor: 'transparent',
  pointerEvents: 'auto',
  animated: false
}

export function useOverlay(userConfig?: Partial<OverlayConfig>): { emitter: Emitter; overlay: HTMLElement } | null {
  const config = { ...defConfig, ...userConfig };
  if (isBrowser) {
    let shouldRemove = false;
    const emitter = mitt();
    const overlay = document.createElement('div');
    overlay.className = 'ant-overlay';
    overlay.style.backgroundColor = config.bgColor;
    overlay.style.pointerEvents = config.pointerEvents;
    if (config.animated) {
      overlay.style.opacity = '0';
    }
    document.body.appendChild(overlay);
    overlay.addEventListener('click', (event: MouseEvent) => {
      emitter.emit<MouseEvent>('click', event);
    });
    overlay.addEventListener('transitionend', () => {
      emitter.emit<void>('transitionend');
      if (shouldRemove) {
        overlay.remove();
        emitter.all.clear();
      }
    });
    emitter.on('remove', () => {
      if (config.animated) {
        shouldRemove = true;
        overlay.style.opacity = '0';
      } else {
        overlay.remove();
        emitter.all.clear();
      }
    });
    if (config.animated) {
      setTimeout(() => {
        overlay.style.opacity = '1';
      }, 0);
    }
    return { emitter, overlay };
  }
  return null;
}
